package com.xiaomaoguai.jdk.collection;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 测试map里放置的定时器任务 是否会替代
 * <p>
 * 这个例子证明了--》map 的 值虽然被替换了，但是之前的定时任务还是会执行
 *
 * @fileName: MapTimerCanOverride.java
 * @author: WeiHui.Zhang
 * @date: 2016-11-16  10:21
 * @version: v1.0.0
 */
public class MapTimerCanOverride {

	private static Map<String, Timer> timerMap = new HashMap<>();

	public static void main(String[] args) throws Exception {
		Timer timer = new Timer();
		timer.schedule(new MyTimerTask("张三"), 10 * 1000);
		timerMap.put("张三", timer);

		Thread.sleep(1);

		if (timerMap.containsKey("张三")) {
			Timer timer1 = timerMap.get("张三");
			if (timer1 != null) {
				timer1.cancel();
			}
		}
		Timer timer2 = new Timer();
		timer2.schedule(new MyTimerTask("张三"), 5 * 1000);
		timerMap.put("张三", timer2);

		System.out.println("Over");
	}


	static class MyTimerTask extends TimerTask {

		String userName;

		public MyTimerTask(String userName) {
			this.userName = userName;
		}

		@Override
		public void run() {
			System.out.println("Your name is : " + userName);
		}
	}

}
